class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {
    // DFS
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(dfs(root.left) - dfs(root.right)) <= 1) {
            return isBalanced(root.left) && isBalanced(root.right);
        }
        return false;
    }

    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftValue = dfs(root.left);
        int rightValue = dfs(root.right);
        return Math.max(leftValue, rightValue) + 1;
    }
}